<?php
declare(strict_types=1);

namespace ServerApp\lib\server\delay_push;

use ServerApp\lib\process\SGlobal;
use ServerApp\lib\process\SPRunnable;
use Tao\src\model\mysql\tao\PushMessageDelay;

/**
 * Class HandleDb
 * @package txz\client\push\server\delay_push
 */
class HandleDb implements SPRunnable
{
    const READ_ROWS = 5000;

    const GIVE_ME_THE_MID = 'a';
    const SLEEP = 'b';
    const WAIT = 'c';

    /**
     * @return mixed|void
     */
    public function run(): void
    {
        tracker("IIIIIIIIIII");
        swoole_event_add(SGlobal::getInstance()->process->pipe, function () {
            $read = SGlobal::getInstance()->process->read();
//            tracker("read", $read);
            if (is_numeric($read)) {
                $read = (int)$read;
                if ($read === 0) {
                    sleep(10);
                }

                $rows = PushMessageDelay::getInstance()->get_push_message_by_cmd($read, HandleDb::READ_ROWS);
                if ($rows && count($rows) > 0) {
                    $key = __DIR__ . '/handle_db';
                    file_put_contents($key, json_encode($rows));
                    SGlobal::getInstance()->process->write($key);
                } else {
                    SGlobal::getInstance()->process->write(self::GIVE_ME_THE_MID);
                }
            } else if ($read === self::WAIT) {
                sleep(10);
                SGlobal::getInstance()->process->write(self::GIVE_ME_THE_MID);
            } else if ($read === self::SLEEP) {
                sleep(30);
                SGlobal::getInstance()->process->write(self::GIVE_ME_THE_MID);
            }
        });

        swoole_timer_tick(1000000, function () {
            if (!PushMessageDelay::getInstance()->removeObj([
                PushMessageDelay::TIME_EXP => ['<', date('Y-m-d H:i:s')]
            ])) {
                tracker(E, PushMessageDelay::getInstance()->getLastSql());
            }
        });

        SGlobal::getInstance()->process->write(self::GIVE_ME_THE_MID);
    }
}